package com.upoint.sellorderservice.service;

import com.upoint.sellorderservice.Constants;
import com.upoint.sellorderservice.domain.order.Order;
import com.upoint.sellorderservice.domain.order.OrderRepository;
import com.upoint.sellorderservice.dto.OrderDto;
import com.upoint.sellorderservice.util.KeyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class OrderService {
    @Resource
    private OrderRepository orderRepository;

    public Order create(OrderDto orderDto, BigDecimal amount) {
        Order order = new Order();
        order.setOrderAmount(amount);
        order.setPayStatus(Constants.PayStatus.WAITING_PAY);
        order.setOrderStatus(Constants.OrderStatus.NEW);
        String orderKey = KeyUtil.generateOrderKey();
        order.setOrderId(orderKey);
        order.setBuyerAddress(orderDto.getAddress());
        order.setBuyerOpenid(orderDto.getOpenid());
        order.setBuyerName(orderDto.getName());
        order.setBuyerPhone(orderDto.getPhone());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        orderRepository.save(order);

        return order;
    }
}
